<!--- 结算汇总 -->
<template>
  <div class="rollup-container">
    <HPCommonPage :titleText="'成本管理 / 结算汇总'">
      <template v-slot:header>
        <el-button type="primary" size="small" @click="onDownMoreOrder"
          >结算单下载</el-button
        >
        <el-button
          type="primary"
          size="small"
          :disabled="isActiveUploadInvoice"
          @click="onUploadInvoice"
          >上传发票</el-button
        >
        <!--- 结算状态：待提交 && 审批状态：已驳回 情况下激活按钮 -->
        <el-button type="primary" size="small" @click="onSummary"
          >一键结算</el-button
        >
      </template>
      <template v-slot:searchForm>
        <el-form
          :inline="true"
          :model="selectData"
          class="form-box res-form-box"
        >
          <el-form-item label="一级部门名称：">
            <el-input
              v-model="selectData.dept"
              clearable
              placeholder="请输入一级部门名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="结算月度：">
            <el-date-picker
              type="months"
              v-model="selectData.months"
              format="yyyy-MM"
              value-format="yyyy-MM"
              placeholder="选择一个或多个月"
            />
          </el-form-item>
          <el-form-item label="结算状态：">
            <el-select
              v-model="selectData.settleState"
              clearable
              placeholder="请选择"
              class="sett-select"
            >
              <el-option
                v-for="item in settleStatus"
                :key="item.key"
                :label="item.label"
                :value="item.key"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="审批状态：">
            <el-select
              v-model="selectData.flowState"
              clearable
              placeholder="请选择"
              class="sett-select"
            >
              <el-option
                v-for="item in approvalStatus"
                :key="item.key"
                :label="item.label"
                :value="item.key"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </template>
      <template v-slot:searchFormbtn>
        <el-button type="success" size="small" @click="onSearch"
          >查询</el-button
        >
      </template>
      <template v-slot:table>
        <HPTable
          :className="'expand-table-box'"
          :tableHeaderItems="tableHeaderItems"
          :tableData="tableData"
          :loading="isLoad"
        >
          <template v-slot:plan="{ data }">
            <!--- 统计一级部门下所有人员已统计百分比 -->
            <el-progress :percentage="data.row.plan"></el-progress>
          </template>
        </HPTable>
      </template>
      <template v-slot:pagination>
        <el-pagination
          v-if="totals"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="selectData.pageNum"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="selectData.pageSize"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="totals"
        >
        </el-pagination>
      </template>
    </HPCommonPage>
    <!---上传发票 -->
    <HPDialog
      title="发票上传"
      :visible.sync="invoiceDialog"
      :confirmBtnText="'确认上传'"
      width="710px"
      :class="'common-dialog-box invoice-dialog'"
      :confirmDisabled="uploadLoading"
      :before-close="onCloseDialog"
      @close-dialog="onCloseDialog"
      @confirm-dialog="onSubmitInvoice"
    >
      <template v-slot:body>
        <el-form
          :model="invoiceForm"
          :rules="invoiceRules"
          ref="invoiceForm"
          label-width="150px"
        >
          <el-form-item label="结算费用（元）：">
            <div class="form-item-border-text">
              {{ invoiceForm.settleCost }}
            </div>
          </el-form-item>
          <el-form-item label="发票上传：" prop="fileList">
            <el-upload
              ref="uploadFile"
              :class="'invoice-upload-box'"
              v-loading="loadingFile"
              action="123"
              :http-request="() => {}"
              :before-upload="onBeforeFileUpload"
              :on-remove="onRemove"
              :limit="3"
              :on-exceed="onExceed"
              :file-list="invoiceForm.fileList"
              list-type="picture-card"
            >
              <i slot="default" class="el-icon-plus"></i>
              <div
                class="el-row--flex justify-content-center"
                slot="file"
                slot-scope="{ file }"
              >
                <!-- pdf展示 -->
                <template v-if="getImageType(file.url)">
                  <img
                    src="../../../assets/images/pdf.png"
                    class="upload-pdf-icon"
                  />
                  <!-- <span class="iconfont icon-PDF upload-pdf-icon"></span> -->
                </template>
                <!-- 其余 -->
                <template v-else>
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="file.url"
                    alt=""
                  />
                </template>

                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="onPreviewImage(file)"
                  >
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span
                    class="el-upload-list__item-delete"
                    @click="onRemove(file, true)"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </el-upload>
            <div class="upload-tip">发票格式支持pdf、png、jpg、jpeg</div>
          </el-form-item>
        </el-form>
      </template>
    </HPDialog>
    <!---一键结算 -->
    <HPDialog
      title="一键结算"
      :visible.sync="rollupVisible"
      :confirmBtnText="'确认提交'"
      width="50%"
      :footer="settlementTableData.length ? true : false"
      :class="'common-dialog-box rollup-dialog'"
      :before-close="() => (rollupVisible = false)"
      @close-dialog="rollupVisible = !rollupVisible"
      @confirm-dialog="onSubmitRollup"
    >
      <template v-slot:body>
        <div class="rollup-dialog-month">结算月度：{{ prevMonth }}</div>
        <HPTable
          :className="'expand-table-box'"
          :tableHeaderItems="settlementTableHeaderItems"
          :tableData="settlementTableData"
          :loading="isSettlementLoad"
          style="height: 400px;"
        />
      </template>
    </HPDialog>
    <!-- 结算单下载 -->
    <HPDialog
      title="结算单下载"
      :visible.sync="downOrderVisible"
      :confirmBtnText="'确认'"
      width="400px"
      :class="'common-dialog-box rollup-dialog'"
      :before-close="onCloseDownOrder"
      @close-dialog="onCloseDownOrder"
      @confirm-dialog="onSubmitDownQuery"
    >
      <template v-slot:body>
        <el-form
          ref="orderForm"
          :model="orderForm"
          :rules="orderFormRules"
          label-width="52px"
          class="demo-ruleForm"
        >
          <el-form-item label="月份" prop="monthly">
            <el-date-picker
              type="months"
              v-model="orderForm.monthly"
              format="yyyy-MM"
              value-format="yyyy-MM"
              placeholder="选择一个或多个月"
            >
            </el-date-picker>
          </el-form-item>
        </el-form>
      </template>
    </HPDialog>
  </div>
</template>
<script>
import HPCommonPage from "@/components/HPCommonPage";
import HPTable from "@/components/HPTable";
import HPDialog from "@/components/HPDialog";
import {
  fetchSummaryList,
  fetchOneClickSettlementList,
  fetchSubmitSettlement,
  fetchSubmitInvoices,
  fetchUploadFile,
  fetchFileList,
  fetchDelInvoice,
  fetchDownSettlementPDF,
  fetchDownSettlementExcel,
  fetchDownMonthSettlementOrder,
  fetchSettleInvoiceList,
} from "@/fetch/modules/rollup";
import { rollupTableColumn, settlementTableHeaderItems } from "../js/column";
import { settleStatus, approvalStatus } from "../js/status";
import getQuery from '@/utils/mixins/getQuery';

export default {
  mixins: [getQuery],
  created() {
    this.getPrevMonthly();
    this.fetchTableData();
  },
  methods: {
    // * 查询条件字段格式化
    formatQuery() {
      const { dept, months, settleState, flowState, pageNum, pageSize } =
        this.selectData || {};
      let monthly = months && months.length ? months.join() : "";
      return {
        dept,
        monthly,
        settleState,
        flowState,
        pageNum,
        pageSize,
      };
    },
    // * 获取结算单列表
    async fetchTableData() {
      this.isLoad = true;
      const { data } = await fetchSummaryList(this.formatQuery());
      if (data.state === "0000") {
        const { list = [], total, lastPage, pageNum } = data.data || {};
        this.tableData = list;
        this.totals = total;
        if(pageNum > lastPage && lastPage > 0) {
            this.selectData.pageNum = lastPage
            this.fetchTableData()
          }
      }
      this.isLoad = false;
    },
    // * 获取一键结算列表
    async fetchSettlementTableData() {
      this.isSettlementLoad = true;
      const { data } = await fetchOneClickSettlementList({
        monthly: this.prevMonth,
      });
      if (data.state === "0000") {
        this.settlementTableData = data.data || [];
      }
      this.isSettlementLoad = false;
    },
    /**
     * 一键结算
     * 数据范围: 上个月且结算状态为已提交、审批状态为未审批的数据;
     * 当审批被流程中心驳回后，该部门单据的审批状态会变更为未审批且再次点击一键结算时，只会统计该部门下被驳回的人员数据
     * */
    async fetchSubmitSettlement() {
      const loading = this.$loading({
        lock: true,
        text: "提交中....",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
        customClass: "require-box",
      });
      const { data } = await fetchSubmitSettlement({ monthly: this.prevMonth });
      if (data.state === "0000") {
        this.tipVisiabled = true;
        this.rollupVisible = false;
        this.settlementTableData = [];
        this.onSearch();
      }
      loading.close();
    },
    // * 发票列表 参数-query: 结算单号
    async fetchInvoicesList(query) {
      this.loadingFile = true;
      const settleNo = query || this.settleNo;
      // const { data } = await fetchFileList({ settleNo });
      const { data } = await fetchFileList({ monthly: this.prevMonth });
      if (data.state === "0000") {
        const { invoiceList, settleCost = 0, invoice } = data.data || {};
        this.invoiceForm.fileList = !invoiceList
          ? []
          : invoiceList.reduce((prev, item) => {
              prev.push({
                name: item.fileName,
                file: item.file,
                id: item.id,
                url: `${window.location.protocol}//${window.location.hostname}/${item.file}`,
              });
              return prev;
            }, []);
        this.invoiceForm.settleCost = settleCost || 0;
        this.isActiveUploadInvoice = !invoice;
      } else {
        this.invoiceForm.fileList = [];
      }
      this.loadingFile = false;
    },
    // * 发票验真 参数-file：文件  settleNo-结算单号
    async fetchInvoicesAuthenticity(fileItem) {
      const loading = this.$loading({
        lock: true,
        text: "上传中....",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
        customClass: "require-box",
      });
      let formData = new FormData();
      formData.append("file", fileItem);
      formData.append("monthly", this.prevMonth);
      const { data } = await fetchUploadFile(formData);

      if (data.state === "0000") {
        // * 发票验证成功，刷新发票列表，关闭加载
        this.fetchInvoicesList();
        loading.close();
        this.uploadLoading = false;
        return Promise.resolve(true);
      } else {
        // * 发票验证失败，移除失败文件，关闭加载
        this.removeErrorFile(fileItem, false);
        loading.close();
        this.uploadLoading = false;
        return Promise.resolve(false);
      }
    },
    // * 删除发票,后刷新发票列表 参数-id:发票id
    async fetchDelectInvoice(id) {
      this.loadingFile = true;
      const { data } = await fetchDelInvoice({ id });
      if (data.state === "0000") {
        this.fetchInvoicesList();
      } else {
        this.loadingFile = false;
      }
    },
    // * 获取上个月
    getPrevMonthly() {
      const nowDate = new Date();
      const year = nowDate.getFullYear();
      const month = nowDate.getMonth();
      const formatMoth = month.toString().padStart(2, "0");
      this.prevMonth = month === 0 ? `${year - 1}-12` : `${year}-${formatMoth}`;
      this.fetchInvoicesList();
    },
    onRejectDetail(row) {
      const { monthly } = row
      console.log(row)
      fetchSettleInvoiceList({
        monthly
      }).then(res => {
        console.log(res)
      })
    },
    // * 结算单下载
    onDownMoreOrder() {
      this.downOrderVisible = true;
    },
    // * 关闭结算单下载弹窗
    onCloseDownOrder() {
      this.$refs["orderForm"].resetFields();
      this.downOrderVisible = false;
      this.isBatch = false;
    },
    // * 提交结算单下载参数并下载
    onSubmitDownQuery() {
      this.$refs.orderForm.validate(async (valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: "结算单下载中....",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
            customClass: "require-box",
          });
          const { monthly } = this.orderForm;
          const result = await fetchDownMonthSettlementOrder({
            monthly: monthly.toString(),
          });
          loading.close();
          if (result.status === 200) {
            if (result.data.size === 0) {
              return this.$message.warning("本月未生成结算单");
            }
            this.downFileMethods(result, "application/pdf;charset=UTF-8");
            this.onCloseDownOrder();
            this.$message.success("下载成功");
          }
        }
      });
    },
    // * 上传发票
    onUploadInvoice() {
      this.invoiceDialog = true;
      this.fetchInvoicesList();
    },
    // * 一键结算
    onSummary() {
      this.fetchSettlementTableData();
      this.rollupVisible = true;
    },
    // * 一键结算-提交结算
    onSubmitRollup() {
      this.fetchSubmitSettlement();
    },
    // * 点击查询
    onSearch() {
      this.selectData.pageNum = 1;
      this.searchData = { ...this.selectData }
      this.fetchTableData();
    },
    // * 发票个数限制
    onExceed(files, fileList) {
      this.$message.warning("仅支持上传3个文件");
    },
    // * 发票上传前校验图片类型"pdf",""png", "jpg", "jpeg"； 图片大小2M
    async onBeforeFileUpload(file) {
      const tempType = file.type.split("/");
      const type = tempType[1];
      const isLt2M = file.size / 1024 / 1024 < 4;
      if (["pdf", "png", "jpg", "jpeg"].includes(type) && isLt2M) {
        const result = await this.fetchInvoicesAuthenticity(file);
        return result;
      } else {
        this.removeErrorFile(file, true);
        return false;
      }
    },
    // * 解决上传失败文件依旧展示问题
    removeErrorFile(file, isShowMessage) {
      let uid = file.uid; // 关键作用代码，去除文件列表失败文件
      let idx = this.$refs.uploadFile.uploadFiles.findIndex(
        (item) => item.uid === uid
      ); // 关键作用代码，去除文件列表失败文件（uploadFiles为el-upload中的ref值）
      this.$refs.uploadFile.uploadFiles.splice(idx, 1); // 关键作用代码，
      if (isShowMessage) {
        this.$message.error("请上传png、jpg、jpeg格式的发票且不能超过2MB！");
      }
    },
    // * 获取图片类型
    getImageType(file) {
      const pdfType = ".pdf";
      if (file) {
        const { length } = file;
        const findType = file.lastIndexOf(pdfType);
        return length - findType === pdfType.length ? true : false;
      }
      return false;
    },
    // * 点击预览验真通过发票
    onPreviewImage(file) {
      this.commonSetPreview(file.url);
    },
    // * 点击删除发票图片 flage： true-手动触发删除  []-自动触发删除
    onRemove(file, flage) {
      if (typeof flage === "boolean") {
        this.fetchDelectInvoice(file.id);
      }
    },
    // * 点击预览
    onPreview(row, column, index, tap) {
      this.commonSetPreview(tap.file);
    },
    // * 关闭发票上传弹窗
    onCloseDialog() {
      this.$refs["invoiceForm"].resetFields();
      this.invoiceForm.fileList = [];
      this.invoiceForm.settleCost = 0;
      this.invoiceDialog = false;
    },
    // * 提交上传发票
    onSubmitInvoice() {
      this.$refs["invoiceForm"].validate(async (valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: "发票信息上传中....",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
            customClass: "require-box",
          });
          const toStrInvoices = this.invoiceForm.fileList
            .map((i) => i.id)
            .join();
          const { data } = await fetchSubmitInvoices({
            monthly: this.prevMonth,
            invoices: toStrInvoices,
          });
          if (data.state === "0000") {
            this.onCloseDialog();
            this.fetchInvoicesList();
            this.onSearch();
          }
          loading.close();
        }
      });
    },
    // * 公共赋值预览
    commonSetPreview(file) {
      window.open(file);
    },
    // * 点击查看
    onLookDetail({ deptName, supplierName, settleNo, monthly, people }) {
      this.$store.commit("STE_INFO", {
        deptName,
        supplierName,
        settleNo,
        monthly,
        people,
      });
      this.$router.push({
        path: `/billingrollup/detail`,
        query: {
          formQuery: JSON.stringify(this.searchData)
        }
      });
    },
    // * 结算单下载
    async onDown({ settleNo }) {
      const loading = this.$loading({
        lock: true,
        text: "结算单下载中....",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
        customClass: "require-box",
      });
      Promise.all([
        fetchDownSettlementPDF({ settleNo }),
        fetchDownSettlementExcel({ settleNo }),
      ]).then((res) => {
        const [settlePDFResult, settleExcelResult] = res;
        if (settlePDFResult.status === 200) {
          console.log(settlePDFResult);
          this.downFileMethods(
            settlePDFResult,
            "application/pdf;charset=UTF-8"
          );
        }
        if (settleExcelResult.status === 200) {
          const { data } = settleExcelResult;
          if (data.state === "0000") {
            const { title, list, head } = data.data;
            this.loadToExclxPlu(head, list, title, data.message);
          }
        }
      });
      loading.close();
    },
    // * 获取文件流的文件名
    getFileStreamName(result) {
      const contentDisposition = result.headers["content-disposition"];
      const fileName = contentDisposition
        ? decodeURIComponent(
            contentDisposition.substring(contentDisposition.indexOf("=") + 8)
          )
        : "";
      return fileName;
    },
    // * 下载PDF方法
    downFileMethods(res, type) {
      const blob = new Blob([res.data], { type });
      let url = window.URL.createObjectURL(blob);
      const fileName = this.getFileStreamName(res);
      let a = document.createElement("a");
      a.style = "display: none";
      document.body.appendChild(a);
      a.href = url;
      a.download = decodeURIComponent(fileName);
      a.click();
      window.URL.revokeObjectURL(url);
    },
    // * 下载excel插件
    loadToExclxPlu(headData, datas, title, message) {
      require.ensure([], () => {
        const { export_json_to_excel } = require("@/exportExcel/Export2Excel");
        if (headData) {
          let thKeys = [],
            tdKeys = [],
            thKey = "",
            thVal = "";
          for (let item in headData) {
            thKey = item;
            thVal = headData[item];
            tdKeys.push(thKey); // 内容
            thKeys.push(thVal); // 头部
          }
          const list = datas;
          const data = this.formatJson(tdKeys, list);
          export_json_to_excel(thKeys, data, title);
          this.$message.success(message);
        }
      });
    },
    // 导出过滤多余字段
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
    // * 切换页条数
    handleSizeChange(val) {
      this.selectData.pageSize = val;
      this.selectData.pageNum = 1;
      this.searchData = { ...this.selectData }
      this.fetchTableData();
    },
    // * 切换页数
    handleCurrentChange(val) {
      this.selectData.pageNum = val;
      this.searchData = { ...this.selectData }
      this.fetchTableData();
    },
  },
  data() {
    return {
      settleStatus: settleStatus, // * 结算状态
      approvalStatus: approvalStatus, // * 审批状态
      prevMonth: "", // * 上个月
      settleNo: "", // * 结算单号
      selectData: {
        // * 查询条件对象
        dept: "",
        months: [],
        settleState: "",
        flowState: "",
        pageNum: 1,
        pageSize: 10,
      },
      tableHeaderItems: rollupTableColumn, // * 一级table字段
      tableData: [],
      totals: 0, // * 一级部门总条数
      isLoad: false, // * 加载动画开关
      uploadLoading: false, // * 发票上传动画
      rollupVisible: false, // * 一键结算列表弹框开关
      settlementTableHeaderItems: settlementTableHeaderItems, // * 一键结算列表字段
      settlementTableData: [], // * 一键结算列表
      isSettlementLoad: false, // * 一键结算列表加载动画
      invoiceDialog: false, // * 发票上传弹窗开关
      loadingFile: false, // * 加载发票列表开关
      isActiveUploadInvoice: false, // * 是否激活上传发票按钮
      invoiceForm: {
        // * 发票上传表单对象
        // deptName: "",
        settleCost: 0,
        fileList: [],
      },
      invoiceRules: {
        // * 发票上传表单校验对象
        fileList: [
          {
            required: true,
            message: "请上传发票",
            trigger: "change",
          },
        ],
      },
      tipVisiabled: false,
      downOrderVisible: false, // * 下载结算单月份弹窗
      orderForm: {
        monthly: [],
      },
      orderFormRules: {
        monthly: [
          {
            required: true,
            message: "请选择月份",
            trigger: "change",
          },
        ],
      },
      isBatch: false, // 是否批量
    };
  },
  components: {
    HPCommonPage,
    HPTable,
    HPDialog,
  },
};
</script>
<style lang="scss">
.rollup-container {
  height: 100%;
  .image-group-box {
    width: 220px;
    overflow: hidden;
    white-space: break-spaces;
    img {
      cursor: pointer;
    }
  }
  .invoice-upload-box {
    .el-upload-list__item-actions {
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
    }
    .el-upload-list__item-actions > span {
      font-size: 15px;
    }
    .el-upload-list__item-actions > span:last-child {
      margin-left: 8px;
    }
    .upload-pdf-icon {
      height: 48px;
    }
  }
}
.rollup-dialog {
  .rollup-dialog-month {
    text-align: left;
    font-weight: bold;
    color: #303133;
    padding-bottom: 10px;
  }
}
</style>
